﻿namespace Collaboris.Saf.Converters.Spring
{
    using System;

    using Definitions;

    using Utils;

    public class DefaultConverter : SafConverter<object>
    {
        public virtual string Convert(object source, bool renderAsTemplate, string propertyName, bool renderAsExpression)
        {
            ValidationHelper.VerifyStringArgument(propertyName, "propertyName");
            ValidationHelper.VerifyObjectArgument(source, "source");

            string attributeName = "value";
            if (renderAsExpression)
                attributeName = "expression";

            string springXml = string.Empty;

            springXml += @"<property name=""" + propertyName + @""" " + attributeName + @"=""" + source.ToString() + @"""/>";

            return springXml;
        }

        public virtual string Convert(SafPropertyDefinition propertyDefinition, bool renderAsTemplate, bool renderAsExpression)
        {
            string springXml = string.Empty;

            string attributeName = "value";
            if (renderAsExpression)
                attributeName = "expression";

            if (renderAsTemplate)
            {
                springXml += @"<property name=""" + propertyDefinition.Name + @""" expression=""" +
                             @"Func.Eval('${" + propertyDefinition.ParentedName.ToLower() + @"}')" + @"""/>";
            }
            else
            {
                // if its primitive or doesnt contain an xml char
                if (propertyDefinition.UnderlyingType.IsPrimitive || IsNotXml(propertyDefinition.Example))
                {
                    springXml += @"<property name=""" + propertyDefinition.Name + @""" " + attributeName + @"=""" +
                                 propertyDefinition.Example + @"""/>";
                }
                else
                {
                    springXml += @"<property name=""" + propertyDefinition.Name + @""">" +
                                 propertyDefinition.Example + @"</property>";
                }
            }
 
            
            return springXml;
        }
    }
}
